unit BubbleSort;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ExtCtrls;

const
  N = 175;
  L = 50;
  w = 5;
  k = 8;
  x0 = 0;
  y0 = 0;
type
  TForm1 = class(TForm)
  Timer1: TTimer;
  Button1: TButton;
  ScrollBar1: TScrollBar;
    Image1: TImage;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Timer1Timer(Sender: TObject);
    procedure ScrollBar1Change(Sender: TObject);
    procedure Button2Click(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  arr: array of integer;
  i, j, t, b, step, runNumber : integer;
implementation

{$R *.dfm}

procedure Draw;
begin
  Form1.Image1.Canvas.Rectangle(0, 0, Form1.Image1.Width, Form1.Image1.Height);
  for b:=0 to N-1 do
  begin
    if (b=step) or (b=step+1) then
      Form1.Image1.Canvas.Brush.Color:=clGreen
    else
      Form1.Image1.Canvas.Brush.Color:=clWhite;
    Form1.Image1.Canvas.Rectangle(x0 + w*b, y0, x0+w*(b+1), y0+k*arr[b]);
  end;
  Form1.Image1.Canvas.Brush.Color:=clWhite;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  runNumber:=0;
  step:=0;
  setlength(arr, N);
  randomize;
  for i:=0 to N-1 do
    arr[i]:=random(L);
  Draw;
  Timer1.Enabled:=True;
end;

procedure TForm1.ScrollBar1Change(Sender: TObject);
begin
  Timer1.Interval:=10*(ScrollBar1.Position)-5;
end;

procedure TForm1.Timer1Timer(Sender: TObject);
begin
  if (runNumber<=N-2) then
  begin
    if (step<=N-2-runNumber) then
    begin
      if (arr[step]>arr[step+1]) then
      begin
        t:=arr[step+1];
        arr[step+1]:=arr[step];
        arr[step]:=t;
        Draw;
        Image1.Refresh;
        step:=step+1;
      end else begin
        Draw;
        step:=step+1;
      end;
    end else begin
      runNumber:=runNumber+1;
      Image1.Refresh;
      step:=0;
    end;
  end else begin
  Timer1.Enabled:=False;
  Application.MessageBox('Sorting Over','The End')
  end;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  if ( Timer1.Enabled=false ) then
    Timer1.Enabled:=true
  else
    Timer1.Enabled:=false;
end;

end.

